﻿// DomainExtractor.cs
// 
// Copyright (C) 2008-2010 Scott Wegner
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Text.RegularExpressions;
using System.Globalization;

namespace PwdhashSharp.Library
{
    /// <summary>
    /// A utility for extracting the domain portion for a URI
    /// </summary>
    public static class DomainExtractor
    {
        #region Public Methods

        /// <summary>
        /// Extract the domain from the passed URI.
        /// </summary>
        /// <param name="host">
        /// The <see cref="System.String"/> URI to be parsed.
        /// </param>
        /// <returns>
        /// The <see cref="System.String"/> domain name
        /// </returns>
        public static string ExtractDomain(string host)
        {
            if (string.IsNullOrEmpty(host))
                throw new ArgumentException("Please enter a valid URI", host);

            string s; // the final result

            // Begin Chris Zarate's code
            host = host.Replace("http://", "");
            host = host.Replace("https://", "");
            Regex re = new Regex("([^/]+)");
            host = re.Match(host).Value;
            string[] hosts = host.Split('.');
            if (hosts.Length >= 3)
            {
                s = hosts[hosts.Length - 2] + '.' + hosts[hosts.Length - 1];
                foreach (string specialDomain in Constants.SpecialDomains)
                {
                    if (s.Equals(specialDomain))
                    {
                        s = hosts[hosts.Length - 3] + '.' + s;
                        break;
                    }
                }
            }
            else
            {
                s = string.Join(".", hosts);
            }
            // End Chris Zarate's code

            Trace.WriteLineIf(PasswordHasher.GeneralSwitch.TraceInfo,
                string.Format(CultureInfo.CurrentCulture, "ExtractDomain final host:\t{0}", host));

            return s;
        }
        #endregion
    }
}
